package cn.openea.perpartner.common.auth.filter;

import cn.openea.perpartner.common.auth.path.impl.AntPathMatcher;
import cn.openea.perpartner.common.auth.config.AuthConfig;
import cn.openea.perpartner.common.auth.entity.LoginBody;
import cn.openea.perpartner.common.auth.entity.R;
import cn.openea.perpartner.common.auth.login.LoginService;
import cn.openea.perpartner.common.auth.util.AuthSpUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Weird077
 * @description TODO
 * @date 2022-07-24 0:12
 */
public class AppFilter implements Filter {
    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private String ssoserver;
    private String logoutpath;
    private String excludedpaths;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ssoserver = filterConfig.getInitParameter(AuthConfig.SSO_SERVER);
        logoutpath = filterConfig.getInitParameter(AuthConfig.SSO_LOGOUT_PATH);
        excludedpaths = filterConfig.getInitParameter(AuthConfig.SSO_EXCLUDED_PATHS);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String reqServletPath = req.getServletPath();
        if (excludedpaths != null && excludedpaths.trim().length() > 0) {
            for (String excludedPath : excludedpaths.split(",")) {
                String uriPattern = excludedPath.trim();
                if (antPathMatcher.match(uriPattern, reqServletPath)) {
                    chain.doFilter(request, response);
                    return;
                }
            }
        }
        LoginService loginService = AuthSpUtil.getBean(LoginService.class);
        if (logoutpath != null && logoutpath.trim().length() > 0 && logoutpath.equals(reqServletPath)) {
            loginService.logout(req);
            res.setStatus(HttpServletResponse.SC_OK);
            res.setContentType("application/json;charset=UTF-8");
            res.getWriter().println("{\"code\":" + R.Type.SUCCESS + ", \"msg\":\"\"}");

            return;
        }
        LoginBody user = loginService.loginCheck(req);
        if (user == null) {
            res.setStatus(HttpServletResponse.SC_OK);
            res.setContentType("application/json;charset=UTF-8");
            res.getWriter().println("{\"code\":" + AuthConfig.SSO_LOGIN_FAIL_RESULT.get(R.CODE_TAG) + ", \"msg\":\"" + AuthConfig.SSO_LOGIN_FAIL_RESULT.get(R.MSG_TAG) + "\"}");
            return;
        }
        request.setAttribute(AuthConfig.SSO_USER, user);
        chain.doFilter(request, response);
    }

}
